package mcia_administrative;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.*;

/**
 * DesktopFloorDesign.java - class used to upload floor image and add lights or CLs
 * 
 * @author MCIA
 */
public class DesktopFloorDesign extends javax.swing.JFrame {

    private int lastNumberOfCL = 0;                                             //initiating counter for units (CL)
    private int floorNumber = 0;                                                //which floor we are at
    private static int CLnum = 0;                                               //used to pass CL number to RoomDesignView
    private static int floorNo = 0;                                             //saving floor number
    private int xM, yM;                                                         //relative Mouse x and y coordinate
    private int x, y;                                                           //used for improvement of button dragging
    private int positionSaved = 0;                                              //checks if the Mouse position is saved to make new CL
    private JLabel pointer1, pointer2, pointer3, pointer4;                      //pointers to see where we add CL
    private int widthCL = 90;                                                   //default width of CL
    private int heightCL = 20;                                                  //default height of CL
    private int widthL = 100;                                                   //default width of Light
    private int heightL = 30;                                                   //default height of Light
    private MouseMotionListener listener;                                       //listener for mouse dragged, etc.
    private MouseListener listener2;                                            //listener for mouse pressed, etc.
    public String currentUser = "admin";                                        //name of current user (get from other window or set still)
    private static String currentCL = "CL";                                     //name of current CL
    private ArrayList<Integer> freeCLNumbers = new ArrayList<Integer>();        //list with CL parameters
    static final String strDirectory = "temp";                                  //name of temporary directory
    static File temp = new File(strDirectory);                                  //file from name of temp directory
    private int loadedUnits = 0;                                                //loading units lock
    private int addingFloor = 0;                                                //adding floor lock
    private int floorNumberTC, clNumberTC, xm2 = 50, ym2 = 20;                  //used for copying CLs

    public DesktopFloorDesign() {
        initComponents();

        //aligning imageLabel position within layeredPane
        int LP_w = layeredPane.getWidth();
        int LP_h = layeredPane.getHeight();
        imageLabel.setBounds(0, 0, LP_w, LP_h);

        //hiding descriptionLabel
        descriptionLabel.setText("");

        //setting text to status label
        statusLabel.setText("User: " + currentUser);

        //setting unvisible poiners
        pointer1 = new JLabel("+");
        pointer2 = new JLabel("+");
        pointer3 = new JLabel("+");
        pointer4 = new JLabel("+");
        pointer1.setName("map_image");
        pointer2.setName("map_image");
        pointer3.setName("map_image");
        pointer4.setName("map_image");
        layeredPane.add(pointer1);
        layeredPane.add(pointer2);
        layeredPane.add(pointer3);
        layeredPane.add(pointer4);
        pointer1.setVisible(false);
        pointer2.setVisible(false);
        pointer3.setVisible(false);
        pointer4.setVisible(false);
        pointer1.setForeground(Color.red);
        pointer2.setForeground(Color.red);
        pointer3.setForeground(Color.red);
        pointer4.setForeground(Color.red);

        //setting name for imageLabel
        imageLabel.setName("map_image");

        //creating directory for storing files
        try {
            boolean success = (temp).mkdir();
            if (success) {
                System.out.println("Directory " + strDirectory + " created: " + temp.getAbsolutePath());
            } else {
                System.out.println("Directory: " + strDirectory + " not created, probably it exists.");
            }
        } catch (Exception e) { //catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

        listener = new MouseMotionListener() {

            public void mouseDragged(MouseEvent e) {
                try {
                    xM = layeredPane.getMousePosition().x - x;
                    yM = layeredPane.getMousePosition().y - y;
                    if (e.getComponent().getHeight() == heightCL) {                 // find witch component is being moved
                        e.getComponent().setBounds(xM, yM, widthCL, heightCL);
                    } else if (e.getComponent().getHeight() == heightL) {
                        e.getComponent().setBounds(xM, yM, widthL, heightL);
                    }
                    repaint();
                } catch (NullPointerException ex) {
                    //we are out of the screen
                }

            }

            public void mouseMoved(MouseEvent e) {
                //nothing happens
            }
        };
        listener2 = new MouseListener() {

            public void mouseClicked(MouseEvent e) {
                // opening window for adding CL Map
                currentCL = e.getComponent().getName();
                int num = e.getComponent().getName().indexOf(".");
                String strnum = e.getComponent().getName().substring(num + 1);
                CLnum = Integer.parseInt(strnum);
                floorNo = floorNumber;
                Main.floorComboIndex = floorCombo.getSelectedIndex();

                DesktopRoomDesign roomDesign = new DesktopRoomDesign();
                Main.changeFrame(roomDesign);
            }

            public void mousePressed(MouseEvent e) {
                //get location where in the component were clicked
                x = e.getX();
                y = e.getY();
            }

            public void mouseReleased(MouseEvent e) {
                //
                String name = e.getComponent().getName();
                int newX = e.getComponent().getX();
                int newY = e.getComponent().getY();

                //
                int firstDot = name.indexOf(".");
                int toDel = Integer.parseInt(name.substring(firstDot + 1));
                toDel -= 1;

                //saving CL to list to remember settings
                String[] unit = new String[]{name, String.valueOf(newX), String.valueOf(newY)};
                Main.allUnits.get(floorNumber).set(toDel, unit); //getting floor and adding unit
            }

            public void mouseEntered(MouseEvent e) {
                //
            }

            public void mouseExited(MouseEvent e) {
                //
            }
        };

        //loading existing units
        if (Main.allUnits.size() > 1) {
            loadedUnits = 1;
            int floor;
            if (DesktopRoomDesign.getFloor() == 0) {
                floor = 1;
            } else {
                floor = DesktopRoomDesign.getFloor();
            }
            int sucess = loadUnits(floor);
            if (sucess == -1) {
                System.out.println("Error: Loading existing units not sucessed!");
            }
            loadedUnits = 0;
            if (floorCombo.getItemCount() > 0) {
                floorCombo.setSelectedIndex(Main.floorComboIndex);
            }
        }

        //for 0 floors disactivate adding CLs
        if (floorCombo.getItemCount() == 1 && floorCombo.getSelectedItem().equals("- No Floor -")) {
            addCLButton.setEnabled(false);
            clComboList.setEnabled(false);
            deleteCLButton.setEnabled(false);
            uploadFloorImageButton.setEnabled(false);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileChooser = new javax.swing.JFileChooser();
        fileSaver = new javax.swing.JFileChooser();
        ClosingConfirmation = new javax.swing.JFrame();
        jPanel5 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        OK = new javax.swing.JButton();
        Cancel = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        uploadFloorImageButton = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        deleteCLButton = new javax.swing.JButton();
        clComboList = new javax.swing.JComboBox();
        addCLButton = new javax.swing.JButton();
        copyCL = new javax.swing.JButton();
        saveProjectButton = new javax.swing.JButton();
        floorCombo = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        backButton = new javax.swing.JButton();
        addFloorButton = new javax.swing.JButton();
        deleteFloorButton = new javax.swing.JButton();
        floorDescription = new javax.swing.JTextField();
        EditGlobal = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        statusLabel = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        descriptionLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        layeredPane = new javax.swing.JLayeredPane();
        imageLabel = new javax.swing.JLabel();

        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.setDialogTitle("Choose Image For The Floor");
        fileChooser.setFileFilter(new MyCustomFilter());

        fileSaver.setDialogTitle("Save Configuration File");
        fileSaver.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
        fileSaver.setFileFilter(new MyCustomFilter2());

        ClosingConfirmation.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        ClosingConfirmation.setTitle("Test");
        ClosingConfirmation.setAlwaysOnTop(true);
        ClosingConfirmation.setBounds(new java.awt.Rectangle(500, 350, 0, 0));
        ClosingConfirmation.setMaximizedBounds(new java.awt.Rectangle(300, 300, 0, 0));
        ClosingConfirmation.setMinimumSize(new java.awt.Dimension(318, 153));
        ClosingConfirmation.setName("closeConfirmation"); // NOI18N
        ClosingConfirmation.setResizable(false);

        jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel1.setText("Do you really want to quit?");

        OK.setText("OK");
        OK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OKActionPerformed(evt);
            }
        });

        Cancel.setText("Cancel");
        Cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(OK, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(Cancel))
                    .addComponent(jLabel1))
                .addContainerGap(56, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel1)
                .addGap(36, 36, 36)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Cancel)
                    .addComponent(OK))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout ClosingConfirmationLayout = new javax.swing.GroupLayout(ClosingConfirmation.getContentPane());
        ClosingConfirmation.getContentPane().setLayout(ClosingConfirmationLayout);
        ClosingConfirmationLayout.setHorizontalGroup(
            ClosingConfirmationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        ClosingConfirmationLayout.setVerticalGroup(
            ClosingConfirmationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        ClosingConfirmation.getAccessibleContext().setAccessibleParent(ClosingConfirmation);

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setBounds(new java.awt.Rectangle(0, 0, 800, 600));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        uploadFloorImageButton.setText("Import Image ...");
        uploadFloorImageButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uploadFloorImageButtonActionPerformed(evt);
            }
        });

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "CL Edition", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        deleteCLButton.setText("Delete");
        deleteCLButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteCLButtonActionPerformed(evt);
            }
        });

        clComboList.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "- Select Unit -" }));
        clComboList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clComboListActionPerformed(evt);
            }
        });

        addCLButton.setText("Add CL");
        addCLButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addCLButtonActionPerformed(evt);
            }
        });

        copyCL.setText("Copy");
        copyCL.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyCLActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(addCLButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(clComboList, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deleteCLButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(copyCL, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addCLButton, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)
                    .addComponent(clComboList, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)
                    .addComponent(deleteCLButton, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)
                    .addComponent(copyCL, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        saveProjectButton.setText("Export Project");
        saveProjectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveProjectButtonActionPerformed(evt);
            }
        });

        floorCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "- No Floor -" }));
        floorCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                floorComboActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel2.setText("Floor:");

        backButton.setText("Back");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });

        addFloorButton.setText("Add Floor");
        addFloorButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addFloorButtonActionPerformed(evt);
            }
        });

        deleteFloorButton.setText("Del. Floor");
        deleteFloorButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteFloorButtonActionPerformed(evt);
            }
        });

        floorDescription.setText("add description");
        floorDescription.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                floorDescriptionActionPerformed(evt);
            }
        });
        floorDescription.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                floorDescriptionFocusGained(evt);
            }
        });

        EditGlobal.setText("Edit GS");
        EditGlobal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditGlobalActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(saveProjectButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(uploadFloorImageButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(floorCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(floorDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(addFloorButton)
                        .addGap(5, 5, 5)
                        .addComponent(deleteFloorButton)))
                .addGap(24, 24, 24)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(backButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(EditGlobal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(uploadFloorImageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addComponent(saveProjectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(floorCombo, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE))
                .addGap(5, 5, 5)
                .addComponent(floorDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addFloorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(deleteFloorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(5, 5, 5))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(EditGlobal, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        statusLabel.setText("User: ? |  Floor: ?");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusLabel)
                .addContainerGap(702, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
        );

        jPanel3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("Floor Design View");

        descriptionLabel.setForeground(new java.awt.Color(51, 102, 255));
        descriptionLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        descriptionLabel.setText("Description Label");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(descriptionLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 775, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 775, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(descriptionLabel)
                .addContainerGap())
        );

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        layeredPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        layeredPane.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                layeredPaneMouseClicked(evt);
            }
        });

        imageLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        imageLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        imageLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        imageLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        imageLabel.setBounds(0, 0, 760, 380);
        layeredPane.add(imageLabel, javax.swing.JLayeredPane.DEFAULT_LAYER);
        imageLabel.getAccessibleContext().setAccessibleParent(jScrollPane1);

        jScrollPane1.setViewportView(layeredPane);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 781, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Uploads floor image
     *
     */
    private void uploadFloorImageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadFloorImageButtonActionPerformed
        //method for uploading image file for the floor
        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
                //what to do with the file
                File sourceimage = new File(file.getAbsolutePath());
                Image image = ImageIO.read(sourceimage);
                ImageIcon icon = new ImageIcon(image);
                imageLabel.setIcon(icon);

                //setting image to bottom layer (to show up buttons)
                layeredPane.setLayer(imageLabel, 0);

                //resizing imageLabel and layeredPane to match picture size
                int imgW = icon.getIconWidth();
                int imgH = icon.getIconHeight();
                imageLabel.setBounds(0, 0, imgW, imgH);
                Dimension dims = new Dimension(imgW, imgH);
                layeredPane.setPreferredSize(dims);

                //saving to remembering list
                Main.floorImages.set(floorNumber, file.getAbsolutePath());

                System.out.println("Successfully loaded file.");
            } catch (Exception ex) {
                System.out.println("Problem accessing file " + file.getAbsolutePath() + " Error: " + ex);
                descriptionLabel.setText("Problem accessing file!");
            }
        } else {
            System.out.println("File access cancelled by user.");
        }
    }//GEN-LAST:event_uploadFloorImageButtonActionPerformed

    /**
     * Add CL button
     *
     */
    private void addCLButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addCLButtonActionPerformed
        //showing info when position not clicked
        if (xM == 0 || yM == 0 || positionSaved == 0) {
            descriptionLabel.setText("Click on the image first.");
            return;
        }

        //setting mouse coordinates
        int newX = xM;
        int newY = yM;

        //computing middle of CL to insert button in the middle of mouse coordinates
        newX = newX - (widthCL / 2);
        newY = newY - (heightCL / 2);

        //making new button with CL name where the coordinates were pointed
        int newCLnumber;
        if (freeCLNumbers.isEmpty()) {
            lastNumberOfCL++;
            newCLnumber = lastNumberOfCL;
            //saving CL to RemList
            String[] unit = new String[]{"CL " + floorNumber + "." + newCLnumber, String.valueOf(newX), String.valueOf(newY)};
            floorNumberTC = floorNumber;
            clNumberTC = newCLnumber;
            Main.allUnits.get(floorNumber).add(unit); //getting floor and adding unit
        } else {
            newCLnumber = freeCLNumbers.get(0);
            freeCLNumbers.remove(0);
            //saving CL to RemList
            String[] unit = new String[]{"CL " + floorNumber + "." + newCLnumber, String.valueOf(newX), String.valueOf(newY)};
            floorNumberTC = floorNumber;
            clNumberTC = newCLnumber;
            Main.allUnits.get(floorNumber).set(newCLnumber - 1, unit); //getting floor and adding unit
        }

        JButton newCL = new JButton("CL " + floorNumber + "." + newCLnumber);
        newCL.setName("CL " + floorNumber + "." + newCLnumber);
        CLnum = newCLnumber;
        newCL.setBounds(newX, newY, widthCL, heightCL);
        newCL.addMouseMotionListener(listener);
        newCL.addMouseListener(listener2);
        layeredPane.add(newCL);
        descriptionLabel.setText("");
        positionSaved = 0;

        //setting image to bottom layer (to show up buttons)
        layeredPane.setLayer(imageLabel, 0);

        //hiding positioner (crosses around new CL)
        pointer1.setVisible(false);
        pointer2.setVisible(false);
        pointer3.setVisible(false);
        pointer4.setVisible(false);

        //adding CL to comboList in right position (sort)
        int howMany = clComboList.getItemCount();
        boolean added = false;
        String name = "CL " + floorNumber + "." + newCLnumber;
        for (int i = 0; i < howMany; i++) {
            Object obj = clComboList.getItemAt(i);
            int compare = name.compareToIgnoreCase(obj.toString());
            if (compare <= 0 && (name.length() == obj.toString().length())) {
                clComboList.insertItemAt(newCL.getText(), i);
                added = true;
                break;
            }
        }
        if (!added) {
            clComboList.addItem(newCL.getText());
        }

    }//GEN-LAST:event_addCLButtonActionPerformed

    /**
     * Used to mark position where mouse was clicked
     *
     */
    private void layeredPaneMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_layeredPaneMouseClicked
        //getting mouse coordinates relative to LayeredPane
        xM = layeredPane.getMousePosition().x;
        yM = layeredPane.getMousePosition().y;

        //showing pointer
        pointer1.setVisible(true);
        pointer1.setBounds(xM - (widthCL / 2) - 3, yM - (heightCL / 2) - 10, widthCL, heightCL);
        pointer2.setVisible(true);
        pointer2.setBounds(xM - (widthCL / 2) - 3, yM + (heightCL / 2) - 10, widthCL, heightCL);
        pointer3.setVisible(true);
        pointer3.setBounds(xM + (widthCL / 2) - 3, yM - (heightCL / 2) - 10, widthCL, heightCL);
        pointer4.setVisible(true);
        pointer4.setBounds(xM + (widthCL / 2) - 3, yM + (heightCL / 2) - 10, widthCL, heightCL);

        //showing info that mouse has been clicked
        descriptionLabel.setText("Position saved. Click 'Add CL' to add CL in this point.");
        positionSaved = 1;
    }//GEN-LAST:event_layeredPaneMouseClicked

    /**
     * Export image and txt files to zip
     *
     */
    private void saveProjectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveProjectButtonActionPerformed
        //actions when user clicks 'save'
        //no CLs inserted - we show info
        if (Main.allUnits.size() < 2) {
            descriptionLabel.setText("No items to save. Insert new CL first!");
            return;
        }

        //for every floor file
        for (int i = 1; i < Main.allUnits.size(); i++) {
            if (Main.allUnits.get(i).size() > 0 && !Main.allUnits.get(i).get(0)[0].equals("deleted")) {
                //if not deleted we make a file
                String txtName = Integer.toString(i) + ".txt";
                File f = new File("temp", txtName);
                try {
                    FileWriter fstream = new FileWriter(f);
                    BufferedWriter out = new BufferedWriter(fstream);
                    //for every CL
                    for (int j = 0; j < Main.allUnits.get(i).size(); j++) {
                        String clName = Main.allUnits.get(i).get(j)[0];
                        if (!clName.equals("deleted")) {
                            int firstDot = clName.indexOf(".");
                            String floorNum = clName.substring(3, firstDot);
                            String clNo = clName.substring(firstDot + 1);

                            String line = floorNum + ";" + clNo + ";" + 0 + ";" + Main.allUnits.get(i).get(j)[1] + ";" + Main.allUnits.get(i).get(j)[2] + ";";
                            out.write(line);
                            out.newLine();
                        }
                    }
                    out.close();
                    System.out.println("File saved successfully: " + f);
                } catch (Exception e) { //catch exception if any
                    System.err.println("Error: " + e.getMessage());
                }
            } else if (Main.allUnits.get(i).isEmpty()) {
                //making empty txt file for empty floor (neccessary for import)
                String txtName = Integer.toString(i) + ".txt";
                File f = new File("temp", txtName);
                try {
                    f.createNewFile();
                } catch (IOException ex) {
                    Logger.getLogger(DesktopFloorDesign.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            //saving jpg file
            if (!Main.floorImages.get(i).equals("")) {
                String jpgFileName = Main.floorImages.get(i);
                File f2 = new File("temp", i + ".jpg");
                try {
                    FileChannel srcChannel = new FileInputStream(jpgFileName).getChannel();
                    //open Channel to output file
                    FileChannel dstChannel = new FileOutputStream(f2).getChannel();
                    //copy file
                    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    srcChannel.close();
                    dstChannel.close();
                } catch (IOException e) {
                    System.out.println("Error: Couldn't copy JPG file: " + e);
                }
            }
        }

        //for every CL file
        for (int i = 0; i < Main.allLights.size(); i++) {
            String clName = Main.allLights.get(i)[0];

            String fileName = clName + ".txt";    //setting file name as CL number
            File f = new File("temp", fileName);
            try {
                FileWriter fstream = new FileWriter(f);
                BufferedWriter out = new BufferedWriter(fstream);
                for (int j = 0; j < Main.allLights.size(); j++) {
                    if (Main.allLights.get(j)[0].equals(clName)) {
                        int firstDot = Main.allLights.get(j)[0].indexOf(".");
                        String floorNum = Main.allLights.get(j)[0].substring(3, firstDot);
                        String clNo = Main.allLights.get(j)[0].substring(firstDot + 1);
                        int lastDot = Main.allLights.get(j)[1].lastIndexOf(".");
                        String lightNo = Main.allLights.get(j)[1].substring(lastDot + 1);
                        String line = floorNum + ";" + clNo + ";" + lightNo + ";" + Main.allLights.get(j)[2] + ";" + Main.allLights.get(j)[3] + ";";
                        out.write(line);
                        out.newLine();
                    }
                }
                //Close the output stream
                out.close();
                descriptionLabel.setText("File successfully saved!");
                System.out.println("File saved successfully: " + f);
            } catch (Exception e) {//Catch exception if any
                System.err.println("Error saving txt file: " + e);
            }
        }

        //for every GS file
        for (int i = 0; i < Main.globalScenes.size(); i++) {
            String txtName = "GS" + Integer.toString(i) + ".txt";
            File f = new File("temp", txtName);
            try {
                FileWriter fstream = new FileWriter(f);
                BufferedWriter out = new BufferedWriter(fstream);
                String GSname = Main.globalSceneName.get(i);
                out.write(GSname);
                out.newLine();
                //for every CL
                for (int j = 0; j < Main.globalScenes.get(i).size(); j++) {
                    String clName = Main.globalScenes.get(i).get(j)[0];
                    //getting number of floor and CL
                    int CLnumber1;
                    int floorNumber1;
                    clName = clName.substring(3);
                    StringTokenizer st1 = new StringTokenizer(clName, ".");
                    floorNumber1 = Integer.parseInt(st1.nextToken());
                    CLnumber1 = Integer.parseInt(st1.nextToken());

                    String line = floorNumber1 + ";" + CLnumber1 + ";" + Main.globalScenes.get(i).get(j)[1] + ";" + Main.globalScenes.get(i).get(j)[2] + ";";
                    out.write(line);
                    if (j + 1 != Main.globalScenes.get(i).size()) {
                        //putting new line to the end of file
                        out.newLine();
                    }

                }
                out.close();
                System.out.println("File saved successfully: " + f);
            } catch (Exception e) { //catch exception if any
                System.err.println("Error: " + e.getMessage());
            }
        }

        //saving jpg file
        for (int i = 0; i < Main.floorImages.size(); i++) {
            if (!Main.floorImages.get(i).equals("")) {
                String jpgFileName = Main.floorImages.get(i);
                File f2 = new File("temp", i + ".jpg");
                try {
                    //open Channel to file witch will be copied.
                    FileChannel srcChannel = new FileInputStream(jpgFileName).getChannel();
                    //open Channel to output file
                    FileChannel dstChannel = new FileOutputStream(f2).getChannel();
                    //copy file
                    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    srcChannel.close();
                    dstChannel.close();
                } catch (IOException e) {
                    System.out.println("Error: Couldn't copy JPG file: " + e);
                }
            }
        }

        //copying CL image file
        for (int i = 0; i < Main.allLights.size(); i++) {
            //copy jpg file
            if (Main.allLights.get(i)[4] != null && !Main.allLights.get(i)[4].equals("")) {
                String jpgFileName = Main.allLights.get(i)[4];
                File f2 = new File("temp", Main.allLights.get(i)[0] + ".jpg");
                try {
                    //opening source channel
                    FileChannel srcChannel = new FileInputStream(jpgFileName).getChannel();
                    //opening destination channel
                    FileChannel dstChannel = new FileOutputStream(f2).getChannel();
                    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    srcChannel.close();
                    dstChannel.close();
                } catch (IOException e) {
                    System.out.println("ERROR: Couldn't copy jpg file.");
                }
            }
        }

        //for floor descriptions file
        String txtName = "floorDesc.txt";
        File f = new File("temp", txtName);
        try {
            FileWriter fstream = new FileWriter(f);
            BufferedWriter out = new BufferedWriter(fstream);
            //for every description
            for (int j = 0; j < Main.floorDescriptions.size(); j++) {
                String desc = Main.floorDescriptions.get(j);
                String line = j + ";" + desc + ";";
                out.write(line);
                out.newLine();
            }
            out.close();
            System.out.println("File saved successfully: " + f);
        } catch (Exception e) { //catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

        //---------------------------zip file-----------------------------------------------------
        //setting default name
        File inFolder = new File("temp");                                       //which to zip
        File outFolder = new File("output.zip");                                //output zip name file
        fileSaver.setSelectedFile(outFolder);
        int saveVal = fileSaver.showSaveDialog(this);

        if (saveVal == JFileChooser.APPROVE_OPTION) {
            try {
                ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(fileSaver.getSelectedFile())));
                BufferedInputStream in = null;
                byte[] data = new byte[2048];
                String files[] = inFolder.list();
                for (int i = 0; i < files.length; i++) {
                    in = new BufferedInputStream(new FileInputStream(inFolder.getPath() + "/" + files[i]), 2048);
                    out.putNextEntry(new ZipEntry(files[i]));
                    int count;
                    while ((count = in.read(data, 0, 2048)) != -1) {
                        out.write(data, 0, count);
                    }
                    out.closeEntry();
                }
                out.flush();
                out.close();
                System.out.println("Successfully zipped: " + fileSaver.getSelectedFile());
                descriptionLabel.setText("File successfully exported!");
                JOptionPane.showMessageDialog(this, "Configuration project file has been saved successfully.", "File successfully exported!", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                System.out.println("Error: " + e);
                JOptionPane.showMessageDialog(this, "ERROR: Configuration project file has NOT been saved.\nError message: " + e, "File was not successfully exported!", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            System.out.println("User cancelled saving a file.");
            descriptionLabel.setText("Saving project file cancelled. File not saved!");
        }
        //---------------------------end zip file-----------------------------------------------------

    }//GEN-LAST:event_saveProjectButtonActionPerformed

    /**
     * Deleting particular CL or Light
     *
     */
    private void deleteCLButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteCLButtonActionPerformed
        //actions to delete particular CL or Light
        //we get text of CL from comboList
        String whichToDelete = clComboList.getSelectedItem().toString();
        int selected = clComboList.getSelectedIndex();

        if (selected == 0) {
            descriptionLabel.setText("First select CL/Light from drop-down list!");
        }

        //we make sure that any CL or Light is selected
        if (selected != 0) {
            //we iterate over all components in layeredPane and look for one with the name that we want
            int toDel2 = 0;
            for (int i = 0; i < layeredPane.getComponentCount(); i++) {
                if (whichToDelete != null && whichToDelete.equals(layeredPane.getComponent(i).getName())) {
                    toDel2 = i;
                }
            }
            //adding number to list of free numbers
            int firstDot = whichToDelete.indexOf(".");
            int onlyNo = Integer.parseInt(whichToDelete.substring(firstDot + 1));
            freeCLNumbers.add(onlyNo);
            Collections.sort(freeCLNumbers);

            //removing from comboList
            clComboList.setSelectedIndex(0);
            clComboList.removeItemAt(selected);

            //removing from layeredPane
            layeredPane.remove(toDel2);
            layeredPane.repaint();
            descriptionLabel.setText(whichToDelete + " deleted");

            //removing from remembering list
            String[] empty = new String[]{"deleted", "", ""};
            Main.allUnits.get(floorNumber).set(onlyNo - 1, empty);

            //removing lights from inside CL
            for (int j = 0; j < Main.allLights.size(); j++) {
                for (int i = 0; i < Main.allLights.size(); i++) {
                    if (Main.allLights.get(i)[0].equals(whichToDelete)) {
                        Main.allLights.remove(i);
                    }
                }
            }
        }
    }//GEN-LAST:event_deleteCLButtonActionPerformed

    private void clComboListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clComboListActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_clComboListActionPerformed

    private void OKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKActionPerformed
        //exit program
        WelcomeScreen wlcm = new WelcomeScreen();
        Main.changeFrame(wlcm);
    }//GEN-LAST:event_OKActionPerformed
    /**
     * Show closing confirmation
     *
     */
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        ClosingConfirmation.setVisible(true);// show ClosingConfirmation
    }//GEN-LAST:event_formWindowClosing
    /**
     * Hide closing confirmation
     *
     */
    private void CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelActionPerformed
        ClosingConfirmation.dispose(); // hide closingConfirmation
    }//GEN-LAST:event_CancelActionPerformed

    private void floorComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_floorComboActionPerformed
        //changing floors
        if (floorNumber > 0 && loadedUnits == 0 && !floorCombo.getSelectedItem().equals("- No Floor -")) {
            int comboNo = floorCombo.getSelectedIndex();
            int firstDot = floorCombo.getSelectedItem().toString().indexOf(".");
            int floor = Integer.parseInt(floorCombo.getSelectedItem().toString().substring(0, firstDot));
            floorNumber = floor;
            loadUnits(floor);
            if (imageLabel.getIcon() != null) {
                int iconW = imageLabel.getIcon().getIconWidth();
                int iconH = imageLabel.getIcon().getIconHeight();
                imageLabel.setBounds(0, 0, iconW, iconH);
                Dimension dims = new Dimension(iconW, iconH);
                layeredPane.setPreferredSize(dims);
            }
            floorCombo.setSelectedIndex(comboNo);
        }
    }//GEN-LAST:event_floorComboActionPerformed

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        //back to main screen
        WelcomeScreen wlcm = new WelcomeScreen();
        Main.changeFrame(wlcm);
    }//GEN-LAST:event_backButtonActionPerformed

    private void addFloorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addFloorButtonActionPerformed
        addingFloor = 1;
        //adding floor to combo
        if (floorNumber == 0 || floorCombo.getSelectedItem().equals("- No Floor -")) {
            floorCombo.removeItem("- No Floor -");
        }

        int newFloorNumber;
        String floorName;
        if (Main.freeFloorNumbers.isEmpty()) {
            int howManyFloors = floorCombo.getItemCount();
            if (floorNumber == 0) {
                floorNumber = 1;
            }
            floorNumber = howManyFloors + 1;
            newFloorNumber = floorNumber;
            Main.allUnits.add(floorNumber, new ArrayList<String[]>());
            if (floorDescription.getText().equals("add description")) {
                floorName = "" + newFloorNumber + ". ";
                Main.floorDescriptions.add(floorNumber, "");
            } else {
                floorName = "" + newFloorNumber + ". " + floorDescription.getText();
                Main.floorDescriptions.add(floorNumber, floorDescription.getText());
            }
        } else {
            newFloorNumber = Main.freeFloorNumbers.get(0);
            floorNumber = newFloorNumber;
            Main.freeFloorNumbers.remove(0);
            Collections.sort(Main.freeFloorNumbers);
            Main.allUnits.set(floorNumber, new ArrayList<String[]>());
            if (floorDescription.getText().equals("add description")) {
                floorName = "" + newFloorNumber + ". ";
                Main.floorDescriptions.set(floorNumber, "");
            } else {
                floorName = "" + newFloorNumber + ". " + floorDescription.getText();
                Main.floorDescriptions.set(floorNumber, floorDescription.getText());
            }
        }

        //setting buttons to enabled
        if (newFloorNumber > 0) {
            addCLButton.setEnabled(true);
            clComboList.setEnabled(true);
            deleteCLButton.setEnabled(true);
            uploadFloorImageButton.setEnabled(true);
        }

        //adding floor to comboList in right position (sort)
        int howMany = floorCombo.getItemCount();
        boolean added = false;
        for (int i = 0; i < howMany; i++) {
            String obj = floorCombo.getItemAt(i).toString();
            String stringToCompare = floorName;
            String stringToCompare2 = obj;
            int compare = stringToCompare.compareToIgnoreCase(stringToCompare2);
            int numberLength1 = stringToCompare.indexOf(".");
            int numberLength2 = stringToCompare2.indexOf(".");
            if (compare <= 0 && numberLength1 == numberLength2) {
                floorCombo.insertItemAt(floorName, i);
                added = true;
                break;
            }
        }
        if (added == false) {
            floorCombo.addItem(floorName);
        }

        floorCombo.setSelectedItem(floorName);
        floorDescription.setText("add description");
        clComboList.removeAllItems();
        clComboList.addItem("- Select Unit -");

        //clearing previously added CLs
        clearLayeredPane(layeredPane);
        imageLabel.setIcon(null);
        lastNumberOfCL = 0;

        //adding to remember list
        Main.floorImages.add(floorNumber, "");
        addingFloor = 0;

    }//GEN-LAST:event_addFloorButtonActionPerformed

    private void deleteFloorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteFloorButtonActionPerformed
        //deleting current floor
        if (floorCombo.getItemCount() == 1 && !floorCombo.getSelectedItem().equals("- No Floor -")) {
            return;
        }

        loadedUnits = 1;
        if (floorCombo.getItemCount() <= 1 && !floorCombo.getSelectedItem().equals("- No Floor -")) {
            floorCombo.addItem("- No Floor -");
        }

        int i = floorCombo.getSelectedIndex();

        if (!floorCombo.getSelectedItem().equals("- No Floor -")) {
            //adding floor number to list of free floor numbers
            String currentFloor = floorCombo.getSelectedItem().toString();
            int firstSpacePos = currentFloor.indexOf(".");
            int currentFloorInt = Integer.parseInt(currentFloor.substring(0, firstSpacePos));

            Main.freeFloorNumbers.add(currentFloorInt);
            Collections.sort(Main.freeFloorNumbers);
            floorCombo.removeItemAt(i);

            //removing from remember list
            String[] deleted = new String[]{"deleted", "", "", "", ""};
            ArrayList delFloor = new ArrayList();
            delFloor.add(deleted);

            Main.allUnits.set(currentFloorInt, delFloor);
            Main.floorImages.set(currentFloorInt, "");
            Main.floorDescriptions.set(currentFloorInt, "");
        }

        if (floorCombo.getSelectedItem().equals("- No Floor -") && floorCombo.getItemCount() == 1) {
            addCLButton.setEnabled(false);
            clComboList.setEnabled(false);
            deleteCLButton.setEnabled(false);
        }
        loadedUnits = 0;
    }//GEN-LAST:event_deleteFloorButtonActionPerformed

    private void floorDescriptionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_floorDescriptionActionPerformed
        //no action
    }//GEN-LAST:event_floorDescriptionActionPerformed

    private void floorDescriptionFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_floorDescriptionFocusGained
        floorDescription.setText("");
    }//GEN-LAST:event_floorDescriptionFocusGained

    private void EditGlobalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditGlobalActionPerformed
        GlobalScenes scenesGS = new GlobalScenes();
        scenesGS.setVisible(true);
    }//GEN-LAST:event_EditGlobalActionPerformed

    private void copyCLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyCLActionPerformed
        String whichToCopy = clComboList.getSelectedItem().toString();
        int selected = clComboList.getSelectedIndex();

        if (selected == 0) {
            descriptionLabel.setText("First select CL/Light from drop-down list!");
        }

        //we make sure that any CL is selected
        if (selected != 0) {
            xM = xm2;
            yM = ym2;
            positionSaved = 1;

            addCLButtonActionPerformed(evt);
            clComboList.setSelectedIndex(0);
            for (int i = 0; i < Main.allLights.size(); i++) {
                if (whichToCopy.equals(Main.allLights.get(i)[0])) {
                    String[] lightCo;
                    String clName = "CL " + floorNumberTC + "." + clNumberTC;
                    String temporary = Main.allLights.get(i)[1];
                    temporary = temporary.substring(6);
                    StringTokenizer st1 = new StringTokenizer(temporary, ".");
                    st1.nextToken();
                    st1.nextToken();
                    String lightName = "Light " + floorNumberTC + "." + clNumberTC + "." + st1.nextToken();
                    String xPos = Main.allLights.get(i)[2];
                    String yPos = Main.allLights.get(i)[3];
                    String remImage = Main.allLights.get(i)[4];
                    lightCo = new String[]{clName, lightName, xPos, yPos, remImage};
                    Main.allLights.add(lightCo);

                }
            }
            whichToCopy = whichToCopy.substring(3);
            StringTokenizer st1 = new StringTokenizer(whichToCopy, ".");
            int floorNumber3 = Integer.parseInt(st1.nextToken());
            int CLnumber3 = Integer.parseInt(st1.nextToken());
            String sorFile = "LS" + floorNumber3 + "." + CLnumber3 + ".txt";
            String destFile = "LS" + floorNumberTC + "." + clNumberTC + ".txt";
            File f = new File(strDirectory, sorFile);
            if (f.exists()) {
                copyFile(sorFile, destFile);
            }
            positionSaved = 0;
        }

    }//GEN-LAST:event_copyCLActionPerformed

    private static void copyFile(String sorFile, String destFile) {
        //needed when we copy CL
        try {
            File f1 = new File(strDirectory, sorFile);
            File f2 = new File(strDirectory, destFile);
            if (!f2.exists()) {
                f2.createNewFile();
            }
            InputStream in = new FileInputStream(f1);

            OutputStream out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage() + " in the specified directory.");
            System.exit(0);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * Used to return name of CL which was chosen to edit
     * @return Name of chosen CL (String)
     */
    static String getCurrentCL() {
        // returns name of CL that was chosen to edit
        return currentCL;
    }

    /**
     * Used to return number of CL which was chosen to edit
     * @return Number of chosen CL (int)
     */
    static int getCLnum() {
        // returns number of CL that was chosen to edit
        return CLnum;
    }

    static int getFloorNum() {
        //returning floor number
        return floorNo;
    }

    /**
     * Deleting specified directory
     *
     */
    static public boolean emptyDirectory(File path) {
        //deleting all files from directory
        if (path.exists()) {
            File[] files = path.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    emptyDirectory(files[i]);
                } else {
                    try {
                        if (files[i].delete()) {
                            System.out.println("File " + files[i].getAbsolutePath() + " was deleted.");
                        } else {
                            System.out.println("File " + files[i].getAbsolutePath() + " wasn't deleted. Problem occured.");
                        }
                    } catch (Exception ex) {
                        System.err.println("Unable to delete " + files[i] + "(" + ex.getMessage() + ")");
                    }
                }
            }
        }
        return (true);
    }

    private int loadUnits(int floorNumber) {
        //loading currentFloor
        if (Main.allUnits.size() > floorNumber && addingFloor == 0) {
            //clearing layeredPane
            clearLayeredPane(layeredPane);

            this.floorNumber = floorNumber;
            this.lastNumberOfCL = Main.allUnits.get(floorNumber).size();
            //loading existing components from Main.allUnits variable
            floorCombo.removeAllItems();
            for (int i = 1; i < Main.allUnits.size(); i++) {
                if (Main.allUnits.get(i).size() > 0) {
                    if (!Main.allUnits.get(i).get(0)[0].equals("deleted")) {
                        floorCombo.addItem("" + i + ". " + Main.floorDescriptions.get(i));
                    } else if (Main.allUnits.get(i).size() > 1) {
                        floorCombo.addItem("" + i + ". " + Main.floorDescriptions.get(i));
                    }
                } else {
                    floorCombo.addItem("" + i + ". " + Main.floorDescriptions.get(i));
                }
            }

            //loading image
            if (!Main.floorImages.get(floorNumber).equals("") && !Main.floorImages.get(floorNumber).equals("-")) {
                String path = Main.floorImages.get(floorNumber).toString();
                try {
                    File sourceimage = new File(path);
                    Image image = ImageIO.read(sourceimage);
                    ImageIcon icon = new ImageIcon(image);
                    imageLabel.setIcon(icon);

                    //resizing imageLabel and layeredPane to match picture size
                    int imgW = icon.getIconWidth();
                    int imgH = icon.getIconHeight();
                    imageLabel.setBounds(0, 0, imgW, imgH);
                    Dimension dims = new Dimension(imgW, imgH);
                    layeredPane.setPreferredSize(dims);
                } catch (IOException ex) {
                    Logger.getLogger(DesktopFloorDesign.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                imageLabel.setIcon(null);
            }

            //loading floor CLs
            clComboList.removeAllItems();
            clComboList.addItem("- Select Unit -");

            for (int i = 0; i < Main.allUnits.get(floorNumber).size(); i++) {
                if (!Main.allUnits.get(floorNumber).get(i)[0].equals("deleted")) {
                    int newX = Integer.parseInt(Main.allUnits.get(floorNumber).get(i)[1]);
                    int newY = Integer.parseInt(Main.allUnits.get(floorNumber).get(i)[2]);

                    JButton newCL = new JButton("CL " + floorNumber + "." + (i + 1));
                    newCL.setName("CL " + floorNumber + "." + (i + 1));
                    newCL.setBounds(newX, newY, widthCL, heightCL);
                    newCL.addMouseMotionListener(listener);
                    newCL.addMouseListener(listener2);
                    layeredPane.add(newCL);

                    String name = Main.allUnits.get(floorNumber).get(i)[0];
                    clComboList.addItem(name);
                }
            }

            //setting image to bottom layer (to show up buttons)
            layeredPane.setLayer(imageLabel, 0);

            //saving missing numbers to freeLightsNumbers list
            //finding higher light number
            int lastIndex = Main.allUnits.get(floorNumber).size() + 1;

            if (Main.allUnits.get(floorNumber).size() > 0) {
                int higherNo = lastIndex;

                //looking for missing numbers
                freeCLNumbers.removeAll(freeCLNumbers);
                int found = 0;
                for (int howManyNumbers = 1; howManyNumbers < higherNo; howManyNumbers++) {
                    found = 0;
                    for (int i = 0; i < Main.allUnits.get(floorNumber).size(); i++) {
                        if (!Main.allUnits.get(floorNumber).get(i)[0].equals("deleted")) {
                            String lookFor = "CL " + floorNumber + "." + howManyNumbers;
                            if (Main.allUnits.get(floorNumber).get(i)[0].equals(lookFor)) {
                                found = 1;
                                break;
                            }
                        }
                        if (i == (Main.allUnits.get(floorNumber).size() - 1) && found == 0) {
                            freeCLNumbers.add(howManyNumbers);
                        }
                    }
                }
                Collections.sort(freeCLNumbers);
            }
            /*-------------------------------------------------------------------*/
        } else {
            return -1;
        }

        return 0;
    }

    public void clearLayeredPane(JLayeredPane pane) {
        imageLabel.setName("map_image");
        //deleting all components in layeredPane except of image map
        int howMany = pane.getComponentCount();
        int j = 0;
        while (j < howMany) {
            int i = j;
            int howMany2 = pane.getComponentCount();
            while (i < howMany2) {
                if (pane.getComponent(i).getName() == null || !pane.getComponent(i).getName().equals("map_image")) {
                    pane.remove(i);
                    howMany2 = pane.getComponentCount();
                } else {
                    i++;
                }
            }
            j++;
        }
        pane.repaint();
    }

    /**
     * Setting Windows Look and Feel
     *
     */
    public static void main(String args[]) {

        //setting Windows Look and Feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println("Error setting native LAF: " + ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                //new DesktopFloorDesign().setVisible(true);
                WelcomeScreen thisFrame = new WelcomeScreen();
                String[] vars = null;
                Main.main(vars);
                Main.changeFrame(thisFrame);
            }
        });

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Cancel;
    private javax.swing.JFrame ClosingConfirmation;
    private javax.swing.JButton EditGlobal;
    private javax.swing.JButton OK;
    private javax.swing.JButton addCLButton;
    private javax.swing.JButton addFloorButton;
    private javax.swing.JButton backButton;
    private javax.swing.JComboBox clComboList;
    private javax.swing.JButton copyCL;
    private javax.swing.JButton deleteCLButton;
    private javax.swing.JButton deleteFloorButton;
    private javax.swing.JLabel descriptionLabel;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JFileChooser fileSaver;
    private javax.swing.JComboBox floorCombo;
    private javax.swing.JTextField floorDescription;
    private javax.swing.JLabel imageLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLayeredPane layeredPane;
    private javax.swing.JButton saveProjectButton;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JButton uploadFloorImageButton;
    // End of variables declaration//GEN-END:variables
}
